package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gakki
 * @create 2022/4/30 15:32
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<Employee>();
        employeeLambdaQueryWrapper.eq(employee.getUsername()!=null,Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(employeeLambdaQueryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return Result.error("查无此账户！");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return Result.error("密码错误！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return Result.error("此账户已禁用！");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return Result.success(emp);
    }

    /**
     * 退出登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/logout")
    public Result<Employee> logout(HttpServletRequest request, Employee employee) {
        request.getSession().removeAttribute("employee");
        return Result.success(employee);
    }

    /**
     * 新增员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> addEmployee(HttpServletRequest request, @RequestBody Employee employee) {
        //设置密码,初始密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间，更新时间
        //2022-05-01T21:01:35.131896800 时间格式
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //设置创建者
        //Long createId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(createId);
        //employee.setUpdateUser(createId);
        //执行save语句
        employeeService.save(employee);
        return Result.success("新增员工成功！");
    }

    /**
     * 员工管理分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize, String name) {
        //日志输出
        log.info("员工管理分页查询开始，page={}，pageSize={},name={}", page, pageSize, name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        lambdaQueryWrapper.apply(StringUtils.isNotEmpty(name), "name REGEXP {0}", name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, lambdaQueryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 更改用户的status状态
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> enableOrDisableStatus(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("开始改用户的status状态");
        //获取当前登录用户的id
        Long id = (Long) request.getSession().getAttribute("employee");

        //执行更新操作
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(id);
        employeeService.updateById(employee);

        //返回结果
        return Result.success("status更改成功！");
    }

    /**
     * 根据id查询员工信息进行编辑操作
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> modifyEmployee(@PathVariable Long id) {
        log.info("查询用户信息进行编辑操作id:{}",id);
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return Result.success(employee);
        }
        return Result.error("为查询到对应员工信息！");
    }
}
